package com.zcwin.runner.model;

import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zcwin.runner.database.DAOFactory;
import com.zcwin.runner.database.IDAO;
import com.zcwin.runner.sms.bean.SendSmsBean;
import com.zcwin.runner.sms.bean.SendedSmsBean;
import com.zcwin.runner.sms.bean.SmsConfig;
import com.zcwin.runner.sms.bean.SmsServerConfig;
import com.zcwin.runner.utils.ConfigManager;
import com.zcwin.runner.utils.GTime;

/**
 *
 * 短信发送和状态处理服务
 * @author 王士江
 * @version 1.0
 */
public class SendSmsService 
{
    SendSmsUtil su = new SendSmsUtil();
    QuerySmsUtil qu = new QuerySmsUtil();
    
    String rid = "";
    String smsid = "";
    String content = "";
    String fileno = "";//文件编号
    String mfrom = "";//发件单位
	String mailmjname = "";//密级名称
	String prioname = "";//紧急程序名称
	String sendtime = "";//发件时间
	String recvmobile = "";//接受单位手机号码
	//SMSSTATE,PTIME,PCOUNT,RETRY,SMSID			
    
    
    int clcount = 0;
	int retry = 0;
	int txinterval = Integer.parseInt(ConfigManager.getInstance().getConfigItem("sms.txinterval","5").toString());
	IDAO dao = DAOFactory.getDao("0");
	Map data = null;
	Logger logger = LoggerFactory.getLogger(SendSmsService.class);
	
    public int sendSmsProcess()
    {
    	String tTime = GTime.getTime(GTime.YYYYMMDDhhmmss);
        Vector list = su.querySendData(tTime);
        if(list!=null && list.size()>0) {
            for (int i = 0; i < list.size(); i++) {
                Map data = (HashMap) list.get(i);//一条待处理的业务数据
                content = data.get("subj").toString();//邮件标题
                fileno = data.get("fileno").toString();//文号
                mfrom = data.get("mfrom").toString();//发送单位
                prioname = data.get("prioname").toString();//紧急程度名称
                rid = data.get("id").toString();//邮件主键
                try {
                	clcount = Integer.parseInt(data.get("pcount").toString());
				} catch (Exception e) {
					clcount = 0;
				}
                try {
                	retry = Integer.parseInt(data.get("retry").toString());
                } catch (Exception e) {
                	retry = 3;
                }
                SendSmsBean sb = new SendSmsBean();
                sb.putData(SmsConfig.getConfig());
                sb.setRid(rid);
                sb.setContent(content);
                sb.setClcount(clcount);
                sb.setFileno(fileno);
                sb.setMfrom(mfrom);
                sb.setRetry(retry);
                sb.setPrioname(prioname);
                if(data.get("recvmobile")!=null)
                {
                	sb.setDestAddr(data.get("recvmobile").toString());
                	sb.setDestAddr(sb.getDestAddr().replaceAll("，", ","));
                }
                if (sb.getDestAddr() == null || "".equals(sb.getDestAddr()) || sb.getDestAddr().length() < 11) {
                    //手机号码错误设置状态为8
                    su.setSendError(rid, "8");
                    logger.error("NEWHERO短信发送错误，手机号码不正确：邮件ID="+sb.getRid()+",MOBILE="+sb.getDestAddr());
                    continue;
                }
                //提醒次数达到要求，通过接口将数据停止提醒
                if (clcount >= retry) {
                    su.setSendError(rid, "2");
                    logger.error("NEWHERO短信发送错误，达到错误发送重试次数：邮件ID="+sb.getRid());
                    continue;
                }

                String xml = su.sendSms(SmsConfig.getConfig(), sb);
                if (xml.equals("0")) {
                    su.setSendSucess(sb);
                } else {
                    su.setSendError(sb);
                    logger.error("NEWHERO短信发送错误：邮件ID="+sb.getRid()+"，错误信息："+xml);
                }
            }
            return 1;
        }
        return 0;
    }
    public int querySmsProcess()
    {
    	String tTime = GTime.getTime(GTime.YYYYMMDDhhmmss);
        Vector list = qu.querySendedData();
        if(list!=null && list.size()>0) 
        {
        	for (int i = 0; i < list.size(); i++) {
        		Map data = (HashMap) list.get(i);//一条待处理的业务数据
                rid = data.get("id").toString();//邮件主键
                try {
                	clcount = Integer.parseInt(data.get("pcount").toString());
				} catch (Exception e) {
					clcount = 0;
				}
                try {
                	retry = Integer.parseInt(data.get("retry").toString());
                } catch (Exception e) {
                	retry = 3;
                }
                //提醒次数达到要求，通过接口将数据停止提醒
                if (clcount >= retry) {
                    qu.setQueryError(rid);
                    logger.error("NEWHERO短信发送错误，达到错误发送重试次数：邮件ID="+rid);
                    continue;
                }
                
                SendedSmsBean sb = new SendedSmsBean();
                sb.putData(SmsConfig.getConfig());
                sb.setRid(rid);
                sb.setDestAddr(data.get("recvmobile").toString());
                sb.setDestAddr(sb.getDestAddr().replaceAll("，", ","));
                sb.setSmsid(data.get("smsid").toString());
                sb.setClcount(clcount);
                sb.setRetry(retry);
                String xml = qu.querySms(sb);
                if(xml.indexOf("发送成功")!=-1)
                {
                	//发送成功
                	qu.setQuerySucess(rid);
                }
                else if(xml.indexOf("发送失败")!=-1)
                {
                	qu.setQueryError(rid,sb.getSmscallback());
                	logger.error("NEWHERO短信发送失败：邮件ID="+sb.getRid()+"，查询返回信息："+xml);
                }
            }
        }
        return 1;
    }
    public static void main(String[] args) {
    	System.setProperty("RUNNER.HOME", "D:/workspace3.7/ThreadRunner_TS");
        System.setProperty("user.timezone","GMT+08");
        PropertyConfigurator.configure(System.getProperty("RUNNER.HOME") + "/config/log4j.properties");
        SendSmsService p = new SendSmsService();
        //p.sendSmsProcess();
        p.querySmsProcess();
        //IDAO dao = DAOFactory.getDao("0");
        //Vector ve = dao.selectEx("select * from sys_user", 1); 
        //System.out.println(ve.get(0).toString());
	}
}
